package com.bocai.grainshop.authserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bocai.common.constant.AuthServerConstant;
import com.bocai.common.exception.CodeMnume;
import com.bocai.common.utils.R;
import com.bocai.grainshop.authserver.feign.MemberfeignService;
import com.bocai.grainshop.authserver.feign.SmsSend;
import com.bocai.grainshop.authserver.vo.PhoneVo;
import com.bocai.grainshop.authserver.vo.UserRegisterVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Slf4j
@Controller
public class regController {

    @Autowired
    private SmsSend smsSend;

    @Autowired
    private StringRedisTemplate restTemplate;

    @Autowired
    private MemberfeignService memberfeignService;

    @PostMapping("/test")
    public R get(@RequestBody String name){
        System.out.println(name);
        return R.ok();
    }


    /**
     * @Author: SunJinbo
     * @Description  邮箱验证码   接受的是对象  前台必须json格式
     *
     * 2022/4/10  踩坑
     *   1.@ResponseBody  需要响应json格式时
     *   2.@RequestBody   接受前台传来的json数据  不是接受对象类型可以不是json格式
     *   ajax : data: JSON.stringify(data) 转json字符串
     *   contentType:"application/json;charset=utf-8"
     * @Param [phone]
     * @return com.bocai.common.utils.R
     * @Data Created in 2022/4/9 22:25
     */
    @ResponseBody //需要响应json
    @PostMapping("/email/sendCode")
    public R getCode(@Valid @RequestBody PhoneVo phone, BindingResult result){
            if (result.hasErrors()) {
                List<String> errors = result.getFieldErrors().stream().map((obj) -> {
                    return obj.getDefaultMessage();
                }).collect(Collectors.toList());
                log.error("phone格式不正确{}"+errors.toString());
                return R.error(22,"手机号码错误！");
            } else {
                String redisCode = restTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone.getPhone());

                if (StringUtils.hasText(redisCode)) {
                    long LongTime = Long.parseLong(redisCode.split("_")[1]);
                    if ((System.currentTimeMillis() - LongTime) < 60 * 1000) {
                        log.info("-----------------------------");
                        return R.error(CodeMnume.PHONE_CODE_ERROR.getCode(), CodeMnume.PHONE_CODE_ERROR.getMessage());
                    }
                }

                Integer code = new Random().nextInt(100000);

                restTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone.getPhone(),
                        code.toString() + "_" + System.currentTimeMillis()
                        , 5, TimeUnit.MINUTES);
                log.info("key:{}" + AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);

                smsSend.getCode(phone.getPhone(), code);
            }
        return R.ok();
    }

    /**
     * @Author: SunJinbo
     * @Description  注册重定向
     * @Param []
     * @return java.lang.String
     * @Data Created in 2022/4/10 12:38
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegisterVo userRegisterVo, BindingResult bindingResult,
                         RedirectAttributes redirectAttributes){
        if(bindingResult.hasErrors()){
            //封装错误信息返回前台
            Map<String, String> errors = bindingResult.getFieldErrors().stream().collect(Collectors.toMap(
                    fieldError -> {
                        return fieldError.getField();
                    }, fieldError -> {
                        return fieldError.getDefaultMessage();
                    },(oldValue,newValue)->{return newValue;}
                    //出现重复时，存放最后一次的value
            ));
            //重定向保存请求域中的数据  一闪而过的数据
            redirectAttributes.addFlashAttribute("errors",errors);
            //校验出错转发到注册页 forward:/reg 会报错  请求映射默认支持get
            return "redirect:http://auth.grainshop.com/reg";
        }else{
            @NotEmpty(message = "验证码不能为空") String code = userRegisterVo.getCode();
            String s = restTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX +
                    userRegisterVo.getEmail());
            if (StringUtils.hasText(s)){
                if(code.equalsIgnoreCase(s.split("_")[0])){
                    //验证码使用完 删除验证码 防止二次调用
                    restTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX+userRegisterVo.getEmail());
                    //验证码正确 通过调用远程会员服务注册
                    R r = memberfeignService.registMember(userRegisterVo);
                    Object o = r.get("code");
                    String toJSONString = JSON.toJSONString(o);
                    Integer numCode = JSON.parseObject(toJSONString, new TypeReference<Integer>() {
                    });
                    if(numCode == 0){
                        //成功重定向到登录页
                        return "redirect:http://auth.grainshop.com/login";
                    }else {
                        Map<String,String> errors = new HashMap<>();
                        Object msg = r.get("msg");
                        String string = JSON.toJSONString(msg);
                        String message = JSON.parseObject(string, new TypeReference<String>() {
                        });
                        errors.put("msg",message);
                        redirectAttributes.addFlashAttribute("errors",errors);
                        return "redirect:http://auth.grainshop.com/reg";
                    }
                }else{
                    Map<String,String> errors = new HashMap<>();
                    errors.put("code","验证码错误");
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.grainshop.com/reg";
                }
            }else {
                Map<String,String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.grainshop.com/reg";
            }
        }
    }
}
